package com.yamaha.bikemarket;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.yamaha.bikemarket.api.API;
import com.yamaha.bikemarket.util.LogUtil;
import com.yamaha.bikemarket.util.SCStaticFunc;
import com.yamaha.bikemarket.util.Utils;

public abstract class AMyActivity extends AActivity implements
		View.OnClickListener {

	private final MenuType menuType;
	private final ArrayList<JSONObject> notifyList = new ArrayList<JSONObject>();
	private MyAdapter notifyAdapter;
	private ImageLoader imageLoader;

	private LayoutInflater inflater;

	public AMyActivity(final MenuType menuType) {
		this.menuType = menuType;

		hideInputText();
	}

	@Override
	public void onBackPressed() {

		final RelativeLayout menuPanel = (RelativeLayout) findViewById(R.id.menu_panel);
		final RelativeLayout headerPanel = (RelativeLayout) findViewById(R.id.header_panel);
		final ImageButton button = (ImageButton) headerPanel
				.findViewById(R.id.menu_logo);

		if (menuPanel.getVisibility() == View.VISIBLE) {
			menuPanel.setVisibility(View.GONE);
			button.setVisibility(View.VISIBLE);
			return;
		} else {
			super.onBackPressed();
		}
	}

	protected abstract List<EditText> getEditTexts();

	@Override
	public abstract void onClick(View v);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	protected void hideInputText() {

		final List<EditText> editTexts = getEditTexts();

		if (null != editTexts) {

			for (final EditText editText : editTexts) {
				if (null != editText) {
					final InputMethodManager imm = (InputMethodManager) this
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(editText.getWindowToken(),
							InputMethodManager.RESULT_UNCHANGED_SHOWN);
				}
			}
		}
	}

	private static final class ItemHolder {
		ImageView feed_bg;
		ImageView feed_image;
		TextView username;
		TextView postTime;
		TextView feed_brand;
		TextView feed_model;
		TextView price;
	}

	private final class MyAdapter extends BaseAdapter {

		private boolean isLoading = true;

		public void setLoading(boolean isLoading) {
			this.isLoading = isLoading;
		}

		@Override
		public int getCount() {
			return (isLoading) ? 1 : notifyList.size();
		}

		@Override
		public Object getItem(int position) {
			return notifyList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (isLoading) {
				convertView = inflater.inflate(R.layout.loading_item, parent,
						false);
				convertView.setId(0x0123);
				return convertView;
			}

			if (convertView != null && convertView.getId() == 0x0123) {
				convertView = null;
			}

			ItemHolder holder;
			if (null == convertView) {
				convertView = inflater.inflate(R.layout.feed_item_layout,
						parent, false);
				convertView.setId(0x124 + position);
				holder = new ItemHolder();
				holder.feed_bg = (ImageView) convertView
						.findViewById(R.id.feed_bg);
				holder.feed_image = (ImageView) convertView
						.findViewById(R.id.feed_image);
				holder.username = (TextView) convertView
						.findViewById(R.id.feed_user);
				holder.postTime = (TextView) convertView
						.findViewById(R.id.feed_post_time);
				holder.feed_brand = (TextView) convertView
						.findViewById(R.id.feed_brand);
				holder.feed_model = (TextView) convertView
						.findViewById(R.id.feed_model);
				holder.price = (TextView) convertView
						.findViewById(R.id.feed_price);

				convertView.setTag(holder);
			} else {
				holder = (ItemHolder) convertView.getTag();
			}

			holder.feed_bg.setImageBitmap(null);
			if (position % 2 == 1) {
				holder.feed_bg.setBackgroundResource(R.drawable.cellbg_blue);
			} else {
				holder.feed_bg.setBackgroundResource(R.drawable.cellbg_pink);
			}

			try {
				final JSONObject obj = notifyList.get(position);

				//
				holder.feed_brand.setText("Brand : "
						+ obj.getString("brand_name"));
				holder.feed_model.setText("Model : "
						+ obj.getString("model_name"));
				holder.price.setText("Price : " + obj.getString("price")
						+ " baht");
				holder.username.setText(obj.getString("user_name"));
				holder.postTime.setText(obj.getString("time"));

				final JSONArray pix = obj.getJSONArray("pix");

				holder.feed_image.setImageBitmap(null);
				if (null != pix && pix.length() > 0) {
					final String url = pix.getString(0);

					if (url != null && url.length() > 0) {
						imageLoader.displayImage(url, holder.feed_image);
					}
				}

			} catch (JSONException e) {
				LogUtil.e("Get View", e.getMessage(), e);
			}

			return convertView;
		}

	}

	protected void showInputText(final EditText editText) {
		final InputMethodManager imm = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
	}

	protected void setListenerForMenu() {
		final ImageButton headerLogo = (ImageButton) findViewById(R.id.menu_logo);
		final RelativeLayout menuPanel = (RelativeLayout) findViewById(R.id.menu_panel);
		final ImageButton notifybutton = (ImageButton) menuPanel
				.findViewById(R.id.notifybutton);
		final ImageButton menuButton = (ImageButton) menuPanel
				.findViewById(R.id.menubutton);
		final ImageButton showAllButton = (ImageButton) menuPanel
				.findViewById(R.id.show_all_button);
		final ImageButton wbButton = (ImageButton) menuPanel
				.findViewById(R.id.wb_button);
		final ImageButton wsButton = (ImageButton) menuPanel
				.findViewById(R.id.ws_button);
		final ImageButton bookingButton = (ImageButton) menuPanel
				.findViewById(R.id.booking_button);
		showAllButton.setOnClickListener(this);
		wbButton.setOnClickListener(this);
		wsButton.setOnClickListener(this);
		bookingButton.setOnClickListener(this);
		menuButton.setOnClickListener(this);
		menuPanel.setOnClickListener(this);
		notifybutton.setOnClickListener(this);
		headerLogo.setOnClickListener(this);
	}

	public boolean onMenuClick(View v) {

		// Hide Keyboard
		hideInputText();

		final RelativeLayout menuPanel = (RelativeLayout) findViewById(R.id.menu_panel);

		final RelativeLayout headerPanel = (RelativeLayout) findViewById(R.id.header_panel);
		final ImageButton button = (ImageButton) headerPanel
				.findViewById(R.id.menu_logo);

		final ImageView notifyBg = (ImageView) findViewById(R.id.notify_bg);
		final ImageView menuBg = (ImageView) findViewById(R.id.menu_bg);
		final ImageButton showAllButton = (ImageButton) menuPanel
				.findViewById(R.id.show_all_button);
		final ImageButton wbButton = (ImageButton) menuPanel
				.findViewById(R.id.wb_button);
		final ImageButton wsButton = (ImageButton) menuPanel
				.findViewById(R.id.ws_button);
		final ImageButton bookingButton = (ImageButton) menuPanel
				.findViewById(R.id.booking_button);

		final ListView notifyListView = (ListView) findViewById(R.id.notify_listview);

		switch (v.getId()) {
		case R.id.menu_logo: {
			if (menuPanel.getVisibility() == View.VISIBLE) {
				menuPanel.setVisibility(View.GONE);
				button.setVisibility(View.VISIBLE);

			} else if (menuPanel.getVisibility() == View.GONE) {
				menuPanel.setVisibility(View.VISIBLE);
				menuPanel.bringToFront();
				button.setVisibility(View.INVISIBLE);
			}
		}
			return true;
		case R.id.menu_panel: {
			menuPanel.setVisibility(View.GONE);
			button.setVisibility(View.VISIBLE);
		}
			return true;
		case R.id.notifybutton: {
			menuBg.setVisibility(View.INVISIBLE);
			notifyBg.setVisibility(View.VISIBLE);
			showAllButton.setVisibility(View.INVISIBLE);
			wbButton.setVisibility(View.INVISIBLE);
			wsButton.setVisibility(View.INVISIBLE);
			bookingButton.setVisibility(View.INVISIBLE);

			notifyListView.setVisibility(View.VISIBLE);

			handleNotify();
		}
			return true;
		case R.id.menubutton: {
			menuBg.setVisibility(View.VISIBLE);
			notifyBg.setVisibility(View.INVISIBLE);
			showAllButton.setVisibility(View.VISIBLE);
			wbButton.setVisibility(View.VISIBLE);
			wsButton.setVisibility(View.VISIBLE);
			bookingButton.setVisibility(View.VISIBLE);

			notifyListView.setVisibility(View.INVISIBLE);
		}
			return true;
		case R.id.show_all_button: {
			menuPanel.setVisibility(View.GONE);
			button.setVisibility(View.VISIBLE);

			if (this.menuType != MenuType.SHOW_ALL_BIKE) {
				final Intent intent = new Intent(this, ShowByFragment.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
				startActivity(intent);
			}
		}
			return true;
		case R.id.booking_button: {
			menuPanel.setVisibility(View.GONE);
			button.setVisibility(View.VISIBLE);
			if (this.menuType != MenuType.BOOKING) {
				final Intent intent = new Intent(this, BookingFragment.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
				startActivity(intent);
			}
		}
			return true;
		case R.id.wb_button: {
			menuPanel.setVisibility(View.GONE);
			button.setVisibility(View.VISIBLE);
			if (this.menuType != MenuType.WANT_TO_BUY) {
				final Intent intent = new Intent(this, WantToBuyFragment.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
				startActivity(intent);
			}
		}
			return true;
		case R.id.ws_button: {
			menuPanel.setVisibility(View.GONE);
			button.setVisibility(View.VISIBLE);

			if (this.menuType != MenuType.WANT_TO_SELL) {
				final Intent intent = new Intent(this, WantToSellFragment.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
				startActivity(intent);
			}
		}
			return true;
		}

		return false;
	}

	private void handleNotify() {
		notifyList.clear();

		inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

		notifyAdapter = new MyAdapter();
		notifyAdapter.setLoading(true);
		final ListView notifyListView = (ListView) findViewById(R.id.notify_listview);
		notifyListView.setAdapter(notifyAdapter);

		final DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory().cacheOnDisc().build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext()).defaultDisplayImageOptions(
				defaultOptions).build();
		if (null != imageLoader && imageLoader.isInited()) {
			imageLoader.destroy();
			imageLoader = null;
		}
		imageLoader = ImageLoader.getInstance();
		if (!imageLoader.isInited()) {
			imageLoader.init(config);
		}

		final RequestParams params = new RequestParams();
		params.put("user_id", SCStaticFunc.getUserId(this));

		final String TAG = "Notify";

		final AsyncHttpClient client = new AsyncHttpClient();
		client.post(API.GET_NOTIFICATION, params,
				new MyAsyncHttpResponseHandler(API.GET_NOTIFICATION, this) {

					@Override
					public void onSuccess(final String res) {
						super.onSuccess(res);

						try {
							final JSONObject object = new JSONObject(res);

							final boolean isSuccess = object
									.getBoolean("success");
							if (isSuccess) {

								final JSONArray yearList = object
										.getJSONArray("year");

								SCStaticFunc.setData(AMyActivity.this,
										SCStaticFunc.YEAR, yearList);

								final JSONArray resList = object
										.getJSONArray("message");

								// Convert To java.util.List
								for (int i = 0; i < resList.length(); i++) {
									notifyList.add(resList.getJSONObject(i));
								}

								notifyAdapter.setLoading(false);
								notifyAdapter.notifyDataSetChanged();

							} else {
								final String msg = object.getString("message");

								Utils.showAlertDialog(AMyActivity.this,
										"Error", msg);

							}

						} catch (JSONException e) {
							LogUtil.e(TAG, e.getMessage(), e);
						}

					}
				});
	}
}
